﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class TreeLoader : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //the tree view will Post a parameter root - so if the param 'root' is present generate the Tree view 
        if (Request.Params["root"] != null)
        {
            AsyncTree();
        }
    }


    public void AsyncTree()
    {
        string root = Request.Params["root"];
        string parentID = string.Empty;
        if (root == "source") //for the first time the JQuery tree will send the root param value as "source"
        {
            GenerateTree(Request.QueryString["selectedDrive"]);
        }
        else
        {
            root = root.Replace("[~]", @"\");
            GenerateTree(root);
        }
    }

    private void GenerateTree(string folderPath)
    {
        System.Text.StringBuilder tree = new System.Text.StringBuilder();
        tree.Append("[");
        //loop through each leaf
        foreach (var item in Directory.GetDirectories(folderPath))
        {
            string name = Path.GetFileName(item);
            string path = item.ToString().Replace(@"\", "[~]");
            tree.Append("{");
            //tree.Append(@"<img src='Images/folder.gif' alt='Alternate Text' />");
            tree.Append(@"'text': '").Append(name).Append("',");
            tree.Append("'id': '").Append(path).Append("',");
            tree.Append("'imagepath': '").Append("Images/folder_icon_small.gif").Append("',");

            tree.Append("'hasChildren': true");
            tree.Append("},");
        }

        foreach (var item in Directory.GetFiles(folderPath))
        {
            string name = Path.GetFileName(item);
            string path = item.ToString().Replace(@"\", "[~]");
            tree.Append("{");
            //tree.Append(@"<img src='Images/folder.gif' alt='Alternate Text' />");
            tree.Append(@"'text': '").Append(name).Append("',");
            tree.Append("'id': '").Append(path).Append("',");
            tree.Append("'imagepath': '").Append("Images/flash.png").Append("',");

            tree.Append("'hasChildren': false");
            tree.Append("},");
        }

        //remove the ending comma from the result
        if (tree.Length > 1)
        {
            tree = tree.Remove(tree.Length - 1, 1);
        }
        tree.Append("]");

        //put the result in Response and end the Response
        Response.Write(tree.ToString());
        Response.End();
    }
}